package org.jeecg.modules.mobile.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanExecute;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanExecuteMaterial;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanExecuteMaterialVO;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanExecuteMaterialService;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanExecuteService;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.jeecg.modules.mobile.entity.vo.MobileTakeStockPlanCreateVO;
import org.jeecg.modules.mobile.entity.vo.MobileTakeStockPlanParamVO;
import org.jeecg.modules.mobile.mapper.MobileTakeStockPlanMapper;
import org.jeecg.modules.mobile.service.IMobileTakeStockPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 移动端盘点
 * @Author: jeecg-boot
 * @Date:   2023-10-10
 * @Version: V1.0
 */
@Service
public class MobileTakeStockPlanServiceImpl  implements IMobileTakeStockPlanService {

    @Autowired
    private MobileTakeStockPlanMapper takeStockPlanMapper;
    @Autowired
    private ITakeStockPlanExecuteMaterialService takeStockPlanExecuteMaterialService;
    @Autowired
    private IWmsRepertoryService repertoryService;
    @Autowired
    private IWmsBasicWarehouseService warehouseService;
    @Autowired
    private IWmsBasicWarehouseAreaService warehouseAreaService;
    @Autowired
    private IWmsBasicWarehouseAreaLocationService warehouseAreaLocationService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private ITakeStockPlanExecuteService takeStockPlanExecuteService;

    /**
     * 盘点第二次扫码查询物料编码，批次号
     */
    @Override
    public List<TakeStockPlanExecuteMaterial> queryScan(MobileTakeStockPlanParamVO param) {
        List<TakeStockPlanExecuteMaterial> list = new ArrayList<>();
        List<TakeStockPlanExecuteMaterial> materialList;
        if (StringUtils.isBlank(param.getId())) {
            TakeStockPlanExecuteMaterialVO vo = takeStockPlanExecuteService.getAddDetail(param.getPlanId());
            materialList = vo.getTakeStockPlanExecuteMaterialList();
        } else {
            materialList = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
                    .eq(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId, param.getId()));
        }
        if (CollectionUtils.isEmpty(materialList)) {
            throw new JeecgBootException("待盘点列表为空");
        }
        // 点击＋号
        if (StringUtils.isNotBlank(param.getRepertoryId()) && StringUtils.isBlank(param.getName())) {
            List<TakeStockPlanExecuteMaterial> collect = materialList.stream().filter(a -> ObjectUtil.equal(param.getRepertoryId(), a.getRepertoryId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                throw new JeecgBootException("该物料不在待盘点列表");
            }
            TakeStockPlanExecuteMaterial material = collect.get(0);
            if (StringUtils.isNotBlank(param.getWarehouseAreaId()) && (!ObjectUtil.equal(param.getWarehouseId(), material.getWmsBasicWarehouseId())
                    || !ObjectUtil.equal(param.getWarehouseAreaId(), material.getWmsBasicWarehouseAreaId())
                    || !ObjectUtil.equal(param.getWarehouseAreaLocationId(), material.getWmsBasicWarehouseAreaLocationId()))) {
                // 待盘点有，储位不同，位置错乱
                material.setResult("3");
                if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaId())) {
                    material.setWmsBasicWarehouseAreaName(warehouseAreaService.getById(material.getWmsBasicWarehouseAreaId()).getName());
                }
                if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaLocationId())) {
                    material.setWmsBasicWarehouseAreaLocationName(warehouseAreaLocationService.getById(material.getWmsBasicWarehouseAreaLocationId()).getName());
                }
                list.add(material);
            }
            return list;
        }
        // 已扫描
        List<TakeStockPlanExecuteMaterial> doneList = materialList.stream().filter(a -> StringUtils.isNotBlank(a.getRealCount())).collect(Collectors.toList());
        List<TakeStockPlanExecuteMaterial> done = doneList.stream().filter(a -> {
            if ((param.getName().equals(a.getBatchCode()) || param.getName().equals(a.getMaterialCode())) && param.getWarehouseId().equals(a.getWmsBasicWarehouseId())) {
                if (StringUtils.isBlank(param.getWarehouseAreaId()) && StringUtils.isBlank(param.getWarehouseAreaLocationId())) {
                    return true;
                } else {
                    return param.getWarehouseAreaId().equals(a.getWmsBasicWarehouseAreaId()) && param.getWarehouseAreaLocationId().equals(a.getWmsBasicWarehouseAreaLocationId());
                }
            }
            return false;
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(done)) {
            // 待盘点没有，在已扫描中
            throw new JeecgBootException("该物料已扫描");
        }
        // 待盘点
        List<TakeStockPlanExecuteMaterial> undoList = materialList.stream().filter(a -> StringUtils.isBlank(a.getRealCount())).collect(Collectors.toList());
        List<TakeStockPlanExecuteMaterial> undo = undoList.stream().filter(a -> param.getName().equals(a.getBatchCode()) || param.getName().equals(a.getMaterialCode())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(undo)) {
            // 待盘点没有，盘盈
            throw new JeecgBootException("该物料不在待盘点列表，请在PC端添加该物料");
        }
        for (TakeStockPlanExecuteMaterial material : undo) {
            if (StringUtils.isNotBlank(param.getWarehouseAreaId()) && (!ObjectUtil.equal(param.getWarehouseId(), material.getWmsBasicWarehouseId())
                    || !ObjectUtil.equal(param.getWarehouseAreaId(), material.getWmsBasicWarehouseAreaId())
                    || !ObjectUtil.equal(param.getWarehouseAreaLocationId(), material.getWmsBasicWarehouseAreaLocationId()))) {
                // 待盘点有，储位不同，位置错乱
                material.setResult("3");
            }
            if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaId())) {
                material.setWmsBasicWarehouseAreaName(warehouseAreaService.getById(material.getWmsBasicWarehouseAreaId()).getName());
            }
            if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaLocationId())) {
                material.setWmsBasicWarehouseAreaLocationName(warehouseAreaLocationService.getById(material.getWmsBasicWarehouseAreaLocationId()).getName());
            }
            list.add(material);
        }
        return list;
    }

    /**
     * 根据盘点范围类型查询
     * @param type
     * @return
     */
    @Override
    public List<MobileTakeStockPlanCreateVO> queryByType(String type) {
        List<MobileTakeStockPlanCreateVO> vos = new ArrayList<>();
        if ("5".equals(type)) {
            List<WmsRepertory> list = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                    .isNotNull(WmsRepertory::getProductCode)
                    .ne(WmsRepertory::getProductCode, "")
                    .groupBy(WmsRepertory::getProductCode));
            vos = list.stream().map(a -> {
                MobileTakeStockPlanCreateVO vo = new MobileTakeStockPlanCreateVO();
                vo.setName(a.getProductCode());
                return vo;
            }).collect(Collectors.toList());
        } else if ("1".equals(type)) {
            List<WmsBasicWarehouse> list = warehouseService.list();
            for (WmsBasicWarehouse warehouse : list) {
                MobileTakeStockPlanCreateVO vo = new MobileTakeStockPlanCreateVO();
                vo.setId(warehouse.getId());
                vo.setName(warehouse.getCode());
                vos.add(vo);
            }
        } else {
            String tableName = "";
            if ("2".equals(type)) {
                tableName = "wms_basic_warehouse_area";
            } else if ("3".equals(type)) {
                tableName = "wms_basic_material_type";
            } else if ("4".equals(type)) {
                tableName = "wms_basic_material";
            } else if ("6".equals(type)) {
                tableName = "wms_basic_customer";
            }
            vos = takeStockPlanMapper.queryByType(tableName);
        }
        return vos;
    }

    /**
     * 保存盘点任务
     */
    @Override
    public TakeStockPlanExecuteMaterialVO planSave(BaseFlowDto base) {
        workFlowService.commit(base);
        TakeStockPlanExecuteMaterialVO vo = takeStockPlanExecuteService.getAddDetail(base.getInfoId());
        List<TakeStockPlanExecuteMaterial> list = vo.getTakeStockPlanExecuteMaterialList();
        for (TakeStockPlanExecuteMaterial material : list) {
            material.setWmsBasicWarehouseName(StringUtils.isNotBlank(material.getWmsBasicWarehouseId()) ? warehouseService.getById(material.getWmsBasicWarehouseId()).getName() : "");
            material.setWmsBasicWarehouseAreaName(StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaId()) ? warehouseAreaService.getById(material.getWmsBasicWarehouseAreaId()).getName() : "");
            material.setWmsBasicWarehouseAreaLocationName(StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaLocationId()) ? warehouseAreaLocationService.getById(material.getWmsBasicWarehouseAreaLocationId()).getName() : "");
        }
        return vo;
    }

    /**
     * 小红点
     * @param warehouseId
     * @return
     */
    @Override
    public String getRedNum(String warehouseId) {
        if (StringUtils.isBlank(warehouseId)) {
            return "";
        }
        List<TakeStockPlanExecuteMaterial> list = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
                .eq(TakeStockPlanExecuteMaterial::getWmsBasicWarehouseId, warehouseId));
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> ids = list.stream().map(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId).collect(Collectors.toSet());
            long count = takeStockPlanExecuteService.count(new LambdaQueryWrapper<TakeStockPlanExecute>()
                    .in(TakeStockPlanExecute::getId, ids)
                    .eq(TakeStockPlanExecute::getDocumentStatus, "1"));
            return String.valueOf(count);
        }
        return "";
    }

    /**
     * 待盘点/已扫描 列表
     * @param id
     * @return
     */
    @Override
    public TakeStockPlanExecuteMaterialVO listTake(String id, String type) {
        TakeStockPlanExecuteMaterialVO vo = takeStockPlanExecuteService.getExecuteById(id);
        if ("1".equals(type)) {
            // 待盘点
            List<TakeStockPlanExecuteMaterial> collect = vo.getTakeStockPlanExecuteMaterialList().stream().filter(a -> StringUtils.isBlank(a.getRealCount())).collect(Collectors.toList());
            vo.setTakeStockPlanExecuteMaterialList(collect);
        }
        if ("2".equals(type)) {
            // 已扫描
            List<TakeStockPlanExecuteMaterial> collect = vo.getTakeStockPlanExecuteMaterialList().stream().filter(a -> StringUtils.isNotBlank(a.getRealCount())).collect(Collectors.toList());
            vo.setTakeStockPlanExecuteMaterialList(collect);
        }
        return vo;
    }
}
